package com.example.chat.component;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.concurrent.ConcurrentHashMap;

// 用户在线管理器
@Component
public class OnlineUserManager {

    private ConcurrentHashMap<Integer, WebSocketSession> sessions = new ConcurrentHashMap<>();

    public void online(int userId, WebSocketSession session) {
        if (sessions.get(userId) != null) {
            System.out.println("userId[" + userId + "] 上线失败，已在其它地方上线");
            return;
        }

        sessions.put(userId, session);

        System.out.println("userId[" + userId + "] 上线");
    }

    public void offline(int userId, WebSocketSession session) {

        WebSocketSession existSession = sessions.get(userId);

        // 当多地登录时，登录失败后会触发 offline() ,因此需要核验当前删除的会话是否为本地会话
        if (existSession == session) {

            sessions.remove(userId);

            System.out.println("userId[" + userId + "] 下线");
        }
    }

    public WebSocketSession getSession(int userId) {
        return sessions.get(userId);
    }
}
